import { Platform } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";

// 检测当前运行环境是否为Web
const isWeb = Platform.OS === "web";

// 内存存储，用于SSR环境
const memoryStorage: Record<string, string> = {};

export const storage = {
  getItem: async (key: string) => {
    if (isWeb) {
      if (typeof window !== "undefined") {
        return Promise.resolve(localStorage.getItem(key));
      }
      return Promise.resolve(memoryStorage[key] || null);
    } else {
      return AsyncStorage.getItem(key);
    }
  },
  setItem: async (key: string, value: string) => {
    if (isWeb) {
      // 在Web环境中使用localStorage
      if (typeof window !== "undefined") {
        localStorage.setItem(key, value);
      } else {
        memoryStorage[key] = value;
      }
      return Promise.resolve();
    } else {
      return AsyncStorage.setItem(key, value);
    }
  },
  removeItem: async (key: string) => {
    if (isWeb) {
      if (typeof window !== "undefined") {
        localStorage.removeItem(key);
      } else {
        delete memoryStorage[key];
      }
      return Promise.resolve();
    } else {
      return AsyncStorage.removeItem(key);
    }
  },
};

export default storage;
